package com.helloandroid.models.butie

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.helloandroid.AppUtil
import com.helloandroid.MyApplication
import com.helloandroid.app.model.AppCache
import com.helloandroid.ext.*
import com.helloandroid.tools.Http.asyncHttpReq
import com.helloandroid.tools.MyLog
import com.helloandroid.tools.NetWorkUtil
import com.helloandroid.vo.MeiRiYunDongInfo
import kotlinx.coroutines.launch
import org.json.JSONObject

class SportViewModel : ViewModel() {

    fun getInfo(callback:(Boolean,MeiRiYunDongInfo?)->Unit){

        val info = AppCache.copyMeiRiYunDongInfo()
        if (info != null){
            callback(true,info)
            return
        }

        if (!NetWorkUtil.networkConnected()){
            AppUtil.toast("请打卡网络!")
            callback(false,null)
            return
        }

        viewModelScope.launch {
            val url = "butie/sport/info?user_id=${AppUtil.user.user_id}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseSportInfo)

            if(parseResult.err == 0){
                val mrydInfo = parseResult.obj as MeiRiYunDongInfo
                AppCache.meiRiYunDongInfo = mrydInfo
                callback(true,AppCache.copyMeiRiYunDongInfo())
            }else{
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
                callback(false,null)
            }
        }
    }
}